#!/usr/bin/env bash
# Summary: Detect the file that sets the current phpenv version
set -e
[ -n "$PHPENV_DEBUG" ] && set -x

find_local_version_file() {
  local root="$1"
  while [ -n "$root" ]; do
    if [ -e "${root}/.php-version" ]; then
      echo "${root}/.php-version"
      exit
    elif [ -e "${root}/.phpenv-version" ]; then
      echo "${root}/.phpenv-version"
      exit
    fi
    root="${root%/*}"
  done
}

find_local_version_file "$PHPENV_DIR"
[ "$PHPENV_DIR" = "$PWD" ] || find_local_version_file "$PWD"

global_version_file="${PHPENV_ROOT}/version"

if [ -e "$global_version_file" ]; then
  echo "$global_version_file"
elif [ -e "${PHPENV_ROOT}/global" ]; then
  echo "${PHPENV_ROOT}/global"
elif [ -e "${PHPENV_ROOT}/default" ]; then
  echo "${PHPENV_ROOT}/default"
else
  echo "$global_version_file"
fi
